package my.xh.validate;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;  
  
public class GetParamNamesByJavassist {  
    public static void main(String[] args) throws NotFoundException {  
       /* Person demo = new Person();  
        Class clazz =Person.class;
        Method[] methods = demo.getClass().getDeclaredMethods();  
        for (int i = 0; i < methods.length; i++) {
			System.out.println(methods[i].getName());
        	getParamName(clazz, methods[i]);
        	System.out.println("_______");
		}  */
         
    }

	public static String[] getParamName(Class clazz, Method method) throws NotFoundException {
		String methodName = method.getName(); 
		ClassPool pool = ClassPool.getDefault();  
        pool.insertClassPath(new ClassClassPath(clazz));  
        CtClass cc = pool.get(clazz.getName());  
        CtMethod cm = cc.getDeclaredMethod(methodName);  
        MethodInfo methodInfo = cm.getMethodInfo();  
        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();  
        LocalVariableAttribute attr =   
                (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);  
        if (attr == null) {  
            System.out.println("params is null");  
        }  
        String[] paramNames = new String[cm.getParameterTypes().length];  
        int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;  
        for (int i = 0; i < paramNames.length; i++)  
            paramNames[i] = attr.variableName(i + pos);  
       /* for (int i = 0; i < paramNames.length; i++) {  
            System.out.println(paramNames[i]);  
        }*/
        return paramNames;
	}  
}  